<?php
/**
 * Created by PhpStorm.
 * User: another
 * Date: 2019-04-24
 * Time: 09:18
 */
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Http\Request;
use DB;

class RolesController extends Controller
{
    protected $rolesModel;
    protected $permissionsModel;

    public function __construct()
    {
        $this->rolesModel = new Role();
        $this->permissionsModel = new Permission();
    }

    public function index(Request $request)
    {
        if(!$request->has('page_size'))
            return response()->json(['code'=>'0','message'=>'请上传页面条数']);

        $data = $request->input();
        $roles = $this->rolesModel->getList($data);

        return response()->json(['code'=>'1','message'=>'获取成功','data'=>$roles]);
    }

    public function removeRoles(Request $request)
    {
        if(!$request->has('id')){
            return response()->json(['code'=>'0','message'=>'请上传角色id']);
        }

        $id = $request->input('id');
        $role = $this->rolesModel::findOrFail($id);
        if(empty($role)){
            return response()->json(['code'=>'0','message'=>'请选择角色']);
        }

        if($role->delete()){
            return response()->json(['code'=>'1','message'=>'删除成功']);
        }else{
            return response()->json(['code'=>'0','message'=>'删除失败']);
        }
    }


    public function addRoles(Request $request)
    {
        $data = $request->input();
        $bool_data = $this->getValidator($data);

        if($bool_data['code'] == 0){
            $result['code'] = '0';
            $result['message'] = $bool_data['message'];
            return response()->json($result);
        }


        $bool = $this->rolesModel->addRoles($bool_data['data']);
        return response()->json($bool);
    }

    public function updRoles(Request $request)
    {
        $data = $request->input();
        if(empty($data['id'])){
            $result['code'] = '0';
            $result['message'] = '请选择角色';
            return response()->json($result);
        }

        $bool_data = $this->getValidator($data);

        if($bool_data['code'] == 0){
            $result['code'] = '0';
            $result['message'] = $bool_data['message'];
            return response()->json($result);
        }


        $bool = $this->rolesModel->updRoles($bool_data['data']);
        return response()->json($bool);
    }


    /**
     * 验证
     * @param $data
     * @return array
     */
    public function getValidator($data)
    {
        $validator = \Validator::make($data,[
            //'name'=>'required|min:2',
            'display_name'=>'required',
            //'description'=>'required',
            'q_ids'=>'required',
        ],[
            'required'=>':attribute为必添项',
            'min'=>':attribute长度不符合要求',
        ],[
            //'name'=>'角色标识',
            'display_name'=>'角色名称',
            //'description'=>'角色描述',
            'q_ids'=>'权限id',
        ]);


        //验证失败，并返回第一个报错
        if($validator->fails()) {
            return ['code' => 0, 'message' => $validator->errors()->first()];
        }


        $permissions = $this->permissionsModel->whereIn('id',explode(',',$data['q_ids']))->get(['id'])->toArray();

        $data['ids_arr'] = array_reduce($permissions, function ($result, $value) {
            return array_merge($result, [$value['id']]);
        }, array());
        if(empty($data['ids_arr'])){
            return ['code'=>0,'message'=>'请上传权限'];
        }

        if(empty($data['quanxian_1'])){
            $data['quanxian_1'] = [];
        }

        if(empty($data['quanxian_2'])){
            $data['quanxian_2'] = [];
        }

        if(empty($data['quanxian_3'])){
            $data['quanxian_3'] = [];
        }



        $temporary_json = [
            $data['quanxian_1'],
            $data['quanxian_2'],
            $data['quanxian_3'],
        ];

        $data['description'] = $data['display_name'];
        $data['name'] = substr(md5(time()), 0, 6);
        $data['temporary_json'] = json_encode($temporary_json);
        return ['code'=>1,'message'=>'验证成功','data'=>$data];
    }

    public function allocation(Request $request)
    {
        //查询最低级
        $level = DB::table('permissions')->max('level');
        //查询角色信息
        $roleModel = new Role();
        $html = $roleModel->itemPermissions($level);

        if(!$request->has('role_id')){
            return response()->json(['code'=>'1','message'=>'获取成功','data'=>['items'=>$html,'role_arr'=>[],'temporary_json'=>[]]]);
        }else{
            $role_id = $request->input('role_id');

            $role = $roleModel->getRoles(['id'=>$role_id],['id','temporary_json']);
            if(empty($role)){
                return response()->json(['code'=>'0','message'=>'请上传角色id']);
            }

            //查询选中的权限
            $per_role = DB::table('permission_role')->where('role_id',$role->id)->get(['permission_id']);
            $role_arr = [];
            foreach ($per_role as $key=>$value)
            {
                $role_arr[] = $value->permission_id;
            }

            return response()->json(['code'=>'1','message'=>'获取成功','data'=>['items'=>$html,'role_arr'=>$role_arr,'temporary_json'=>json_decode($role->temporary_json,true)]]);
        }
    }
}
